import 'dart:io';

import 'package:dio_log/interceptor/dio_log_interceptor.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'file:///E:/Kin_Project/flutter_audit_app/lib/ui/login/splash_page.dart';
import 'package:flutter_audit_app/net/api_service.dart';
import 'package:flutter_audit_app/widgets/dismiss_keyboard_widget.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

import 'utils/sputil_key.dart';
import 'localization/app_localizations.dart';
import 'net/dio_utils.dart';
import 'net/interceptors.dart';
import 'provider/theme_provider.dart';
import 'routes/404.dart';
import 'routes/routers.dart';
import 'utils/log_utils.dart';

import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  ///sp初始化
  await SpUtil.getInstance();
  runApp(MyApp());

  ///透明状态栏
  if (Platform.isAndroid) {
    SystemUiOverlayStyle systemUiOverlayStyle =
        SystemUiOverlayStyle(statusBarColor: Colors.transparent); //设置为透明
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
}

class MyApp extends StatelessWidget {
  MyApp() {
    Log.init();
    _initDio();
    Routes.initRoutes();
  }

  void _initDio() {
    final List<Interceptor> interceptors = [];

    ///统一添加身份验证请求头
    interceptors.add(AuthInterceptor());

    ///刷新Token
    interceptors.add(TokenInterceptor());

    ///打印Log(生产模式去除)
    if (!SpKey.inProduction) {
      interceptors.add(LoggingInterceptor());
    }

    ///适配数据(根据自己的数据结构，可自行选择添加)
    interceptors.add(AdapterInterceptor());

    ///开发阶段添加显示打印日志
    interceptors.add(DioLogInterceptor());
    setInitDio(
      baseUrl: ApiService.root,
      interceptors: interceptors,
    );
  }

  @override
  Widget build(BuildContext context) {
    return OKToast(
        child: ChangeNotifierProvider<ThemeProvider>(
          create: (_) => ThemeProvider(),
          child: Consumer<ThemeProvider>(
            builder: (context, provider, child) {
              return MaterialApp(
                title: '移动稽核',
                debugShowCheckedModeBanner: false,
                // 去除右上角debug的标
                theme: provider.getTheme(),
                darkTheme: provider.getTheme(isDarkMode: true),
                themeMode: provider.getThemeMode(),
                home: DismissKeyboardWidget(),
                onGenerateRoute: Routes.router.generator,
                localizationsDelegates: const [
                  AppLocalizationsDelegate(),
                  GlobalMaterialLocalizations.delegate,
                  GlobalWidgetsLocalizations.delegate,
                  GlobalCupertinoLocalizations.delegate,
                ],
                supportedLocales: const <Locale>[
                  Locale('zh', 'CN'),
                  Locale('en', 'US'),
                ],

                /// 保证文字大小不受手机系统设置影响 https://www.kikt.top/posts/flutter/layout/dynamic-text/
                builder: (context, child) => MediaQuery(
                  // 或者 MediaQueryData.fromWindow(WidgetsBinding.instance.window).copyWith(textScaleFactor: 1.0),
                  data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
                  child: GestureDetector(
                    onTap: () {
                      FocusScopeNode currentFocus = FocusScope.of(context);
                      if (!currentFocus.hasPrimaryFocus &&
                          currentFocus.focusedChild != null) {
                        FocusManager.instance.primaryFocus.unfocus();
                      }
                    },
                    child: child,
                  ),
                ),

                /// 因为使用了fluro，这里设置主要针对Web
                onUnknownRoute: (_) {
                  return MaterialPageRoute(
                    builder: (BuildContext context) => NotFoundPage(),
                  );
                },
              );
            },
            /*builder: (_, provider, __) => MaterialApp(
              title: '移动稽核',
              debugShowCheckedModeBanner: false, // 去除右上角debug的标
              theme: provider.getTheme(),
              darkTheme: provider.getTheme(isDarkMode: true),
              themeMode: provider.getThemeMode(),
              home: SplashPage(),
              onGenerateRoute: Routes.router.generator,
              localizationsDelegates: const [
                AppLocalizationsDelegate(),
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
                GlobalCupertinoLocalizations.delegate,
              ],
              supportedLocales: const <Locale>[
                Locale('zh', 'CN'),
                Locale('en', 'US'),
              ],

              /// 保证文字大小不受手机系统设置影响 https://www.kikt.top/posts/flutter/layout/dynamic-text/
              builder: (context, child) => MediaQuery(
                // 或者 MediaQueryData.fromWindow(WidgetsBinding.instance.window).copyWith(textScaleFactor: 1.0),
                data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
                child: child,
              ),

              /// 因为使用了fluro，这里设置主要针对Web
              onUnknownRoute: (_) {
                return MaterialPageRoute(
                  builder: (BuildContext context) => NotFoundPage(),
                );
              },
            ),*/
          ),
        ),

        /// Toast 配置
        backgroundColor: Colors.black54,
        textPadding:
            const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
        radius: 20.0,
        position: ToastPosition.center);
  }
}
